package saer.send.now.operations;

import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import saer.send.now.channel.Channel;
import saer.send.now.channel.State;

public class GetStatus implements IOperation {
    public static String        OP_CODE = "gs";

    private static final Logger log     = Logger.getLogger(GetStatus.class.getName());

    @Override
    public void exec(Map<String, Channel> channelStore, String id, HttpServletRequest req, HttpServletResponse resp) {
        log.log(Level.FINEST, "Got GET_STATUS request, {0}", req);
        if (id == null) {
            log.log(Level.WARNING, "Id is missing, req:{0}", req);
            resp.setStatus(500);
            return;
        }

        Channel channel = channelStore.get(id);
        if (channel == null) {
            log.log(Level.FINER, "Got first request, creating channel, req:{0}, id:{1}", new Object[] { req, id });
            channel = new Channel(id, new State(resp));
            channelStore.put(id, channel);
        }

        String status = channel.getState().getStatus();

        try {
            resp.getWriter().write(status);
        } catch (IOException e) {
            log.log(Level.WARNING, "Failed to get status, id:{0}, e:{1}", new Object[] { id, e });
            throw new RuntimeException("Failed to get status, id:" + id, e);
        }

        if (channel.getState().isDone()) {
            channelStore.remove(id);
        }
    }
}
